var createError = require('http-errors');
var express = require('express');
var path = require('path');
const ejs = require('ejs');
// 加载cookie模块，用于获取web浏览器发送的cookis中的内容
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//解析客户端请求的body中的内容,内部使用JSON编码处理,url编码处理以及对于文件的上传处理
var bodyParser = require('body-parser');

// 生成一个express实例
var app = express();

// 设置views, __dirname是node全局变量，取得当前js的绝对路径
app.set('views', path.join(__dirname, 'views'));
// 修改成html模板
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
// 设置允许跨域请求
app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By","nodejs");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});
// 加载日志中间件
app.use(logger('dev'));
// 使用插件 解析json的中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 设置/routes/config文件为总路由控制文件
// 在/routes/config文件中做统一路由分发
var config = require('./routes/config');
config(app)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
